package org.crystalrange.files.web;

import org.crystalrange.BaseController;
import org.crystalrange.Message;
import org.crystalrange.files.model.FileType;
import org.crystalrange.files.service.FileTypeService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;

public class FileTypeController extends BaseController {
	
	private FileType fileType;
	private FileTypeService fileTypeService;
	
	public FileType getFileType() {
		return fileType;
	}
	public void setFileType(FileType fileType) {
		this.fileType = fileType;
	}
	public FileTypeService getFileTypeService() {
		return fileTypeService;
	}
	public void setFileTypeService(FileTypeService fileTypeService) {
		this.fileTypeService = fileTypeService;
	}
	
	public void onClick$toolbarbuttonFileTypeSave(Event event) throws Exception {
        this.fileTypeSave();
    }
    
    public void onClick$menuitemFileTypeSave(Event event) throws Exception {
        this.fileTypeSave();        
    } 
    
    private void fileTypeSave() throws Exception {
    	if (this.fileType.getName() != null && this.fileType.getExtension() != null && this.fileType.getIcon() != null) {
    		this.fileTypeService.save(this.fileType);
    		this.sessionScope.put("CRYSTALRANGE_MESSAGE", new Message("Saved successfully!"));
    		Clients.evalJavaScript("window.history.back();");
		} else {
			this.message.setText("You must enter 'Type Name', 'Type Extension' and 'Type Icon'.");
            this.message.setIcon("/img/exclamation.png");
            this.binder.loadAll();
		}
    }
	
	@Override
    public void doAfterCompose(Component component) throws Exception {
        super.doAfterCompose(component);
        
        if (this.execution.getParameter("Id") != null) {
            this.fileType = this.fileTypeService.find(
                    Long.parseLong(this.execution.getParameter("Id")));
            this.labelTitle.setValue("Edit File Type");
        } else {
            this.fileType = this.fileTypeService.create(
                    SecurityContextHolder.getContext().getAuthentication().getName());
            this.labelTitle.setValue("Create File Type");
        }

        component.setAttribute("controller", this);
    }
}
